// 聊天功能模块

// 聊天管理类
class ChatManager {
    constructor() {
        this.chatMessages = document.getElementById('chat-messages');
        this.messageInput = document.getElementById('message-input');
        this.sendButton = document.getElementById('send-button');
        
        this.init();
    }
    
    init() {
        this.bindEvents();
    }
    
    bindEvents() {
        // 发送消息事件
        this.sendButton.addEventListener('click', () => {
            this.sendMessage();
        });
        
        // 回车发送消息
        this.messageInput.addEventListener('keypress', (e) => {
            if (e.key === 'Enter') {
                this.sendMessage();
            }
        });
    }
    
    sendMessage() {
        const message = this.messageInput.value.trim();
        if (!message) return;
        
        // 添加用户消息到聊天界面
        this.addMessage('user', message);
        
        // 清空输入框
        this.messageInput.value = '';
        
        // 显示"正在输入"指示器
        const typingIndicator = this.addMessage('character', '正在输入...', true);
        
        // 模拟API调用延迟
        setTimeout(() => {
            // 移除"正在输入"指示器
            this.chatMessages.removeChild(typingIndicator);
            
            // 生成角色回复
            const reply = window.characterManager.generateReply(message);
            this.addMessage('character', reply);
            
            // 滚动到底部
            this.chatMessages.scrollTop = this.chatMessages.scrollHeight;
        }, 1000 + Math.random() * 1000);
    }
    
    addMessage(sender, content, isTyping = false) {
        const messageDiv = document.createElement('div');
        messageDiv.className = `message ${sender === 'user' ? 'user-message' : 'character-message'}`;
        
        if (!isTyping) {
            const senderDiv = document.createElement('div');
            senderDiv.className = 'message-sender';
            senderDiv.textContent = sender === 'user' ? '你' : window.characterManager.getCurrentCharacter().name;
            messageDiv.appendChild(senderDiv);
        }
        
        const contentDiv = document.createElement('div');
        contentDiv.className = 'message-content';
        contentDiv.textContent = content;
        messageDiv.appendChild(contentDiv);
        
        this.chatMessages.appendChild(messageDiv);
        this.chatMessages.scrollTop = this.chatMessages.scrollHeight;
        
        return messageDiv;
    }
    
    addSystemMessage(content) {
        this.addMessage('system', content);
    }
    
    clearChat() {
        this.chatMessages.innerHTML = '';
    }
}

// 导出聊天管理器
window.chatManager = new ChatManager();